﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Threading.Tasks;

namespace MDT_Metro_monitoring
{
    public static class DataServiceContextAsyncExtensions
    {
        public static async Task<IEnumerable<TResult>> ExecuteAsync<TResult>(this DataServiceQuery<TResult> query)
        {
            var queryTask = Task.Factory.FromAsync<IEnumerable<TResult>>(query.BeginExecute(null, null), (asResult) =>
            {
                IEnumerable<TResult> result = null;
                try
                {
                    result = query.EndExecute(asResult).ToList();
                }
                catch (Exception)
                {
                    //throw new Exception("Server is offline");
                }
                return result;
            });

            return await queryTask;
        }

        public static async Task<IEnumerable<TResult>> ExecuteAsync<TResult>(this DataServiceContext context, Uri requestUri)
        {
            var executeTask = Task.Factory.FromAsync<IEnumerable<TResult>>(context.BeginExecute<TResult>(requestUri, null, null),
                       (executeAsyncResult) =>
                       {
                           var executeResult = context.EndExecute<TResult>(executeAsyncResult).ToList();
                           return executeResult;
                       });

            return await executeTask;
        }
    }
}
